package com.zx.zxojbackendjudge.strategy;



import com.zx.zxojbackendcommon.exception.BusinessException;
import com.zx.zxojbackendmodel.dto.judge.ExecuteCodeResponse;
import com.zx.zxojbackendmodel.dto.judge.JudgeInfo;
import com.zx.zxojbackendmodel.dto.question.JudgeCase;
import com.zx.zxojbackendmodel.dto.question.JudgeConfig;
import com.zx.zxojbackendmodel.enums.JudgeInfoMessageEnum;

import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 使用java语言的判题策略
 */
public class JavaLanguageStrategy implements Strategy{
    @Override
    public JudgeInfo doJudge(JudgeContext judgeContext) {
        List<String> inputs = judgeContext.getInputs();
        ExecuteCodeResponse executeCodeResponse = judgeContext.getExecuteCodeResponse();
        JudgeConfig judgeConfig = judgeContext.getJudgeConfig();
        List<JudgeCase> judgeCase = judgeContext.getJudgeCase();
        List<String> outputs = executeCodeResponse.getOutputList();
        JudgeInfo judgeInfo = executeCodeResponse.getJudgeInfo();
        if(judgeInfo == null){
            //直接返回错误信息
            return judgeInfo;

        }
        judgeInfo.setMessage(JudgeInfoMessageEnum.ACCEPTED.getValue());
        //个数不一致，直接判错
        if(outputs.size() != inputs.size()){
            judgeInfo.setMessage(JudgeInfoMessageEnum.WRONG_ANSWER.getValue());
            return judgeInfo;
        }
        //逐个判断答案
        for (int i = 0; i < outputs.size(); i++) {
            if(!judgeCase.get(i).getOutput().equals(getNumber(outputs.get(i)))){
                judgeInfo.setMessage(JudgeInfoMessageEnum.WRONG_ANSWER.getValue());
                return judgeInfo;
            }
        }
        //判断内存
        if(judgeInfo.getMemory() == null || judgeInfo.getMemory() > judgeConfig.getMemoryLimit()){
            judgeInfo.setMessage(JudgeInfoMessageEnum.MEMORY_LIMIT_EXCEEDED.getValue());
            return judgeInfo;
        }
        //判断时间
        if(judgeInfo.getTime() == null || judgeInfo.getTime() > judgeConfig.getTimeLimit()){
            judgeInfo.setMessage(JudgeInfoMessageEnum.TIME_LIMIT_EXCEEDED.getValue());
            return judgeInfo;
        }
        return judgeInfo;
    }
    private String getNumber(String str){
        String regex = "\\d+"; // 正则表达式
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(str);
        boolean result = matcher.find();
        if (result) {
            String group = matcher.group(0);
            return group;
        } else {
            throw new BusinessException(500,"没有提取到数字部分");
        }
    }
}
